// 登录注册页面JavaScript

document.addEventListener('DOMContentLoaded', function() {
    console.log('认证页面已加载');
    
    // 检查是登录页面还是注册页面
    const isLoginPage = document.getElementById('loginForm') !== null;
    const isRegisterPage = document.getElementById('registerForm') !== null;
    
    if (isLoginPage) {
        initLogin();
    }
    
    if (isRegisterPage) {
        initRegister();
    }
});

// 登录页面初始化
function initLogin() {
    const loginForm = document.getElementById('loginForm');
    const loginBtn = document.getElementById('loginBtn');
    
    loginForm.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;
        
        // 清除之前的错误
        clearErrors('loginForm');
        
        // 验证输入
        if (!username) {
            showError('usernameError', '请输入用户名');
            return;
        }
        
        if (!password) {
            showError('passwordError', '请输入密码');
            return;
        }
        
        // 显示加载状态
        loginBtn.disabled = true;
        loginBtn.querySelector('span:first-child').style.display = 'none';
        loginBtn.querySelector('.btn-loading').style.display = 'inline';
        
        try {
            // 发送登录请求
            const response = await fetch('/api/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ username, password })
            });
            
            console.log('登录响应状态:', response.status);
            console.log('Content-Type:', response.headers.get('Content-Type'));
            
            // 检查响应类型
            const contentType = response.headers.get('Content-Type') || '';
            if (!contentType.includes('application/json')) {
                const text = await response.text();
                console.error('响应不是JSON:', text);
                throw new Error('服务器返回了非JSON数据');
            }
            
            const data = await response.json();
            
            if (data.success) {
                // 登录成功
                showSuccessMessage('✅ 登录成功！正在跳转...');
                
                // 保存用户信息
                localStorage.setItem('lastLoginUsername', username);
                
                // 延迟跳转，让用户看到成功提示
                setTimeout(() => {
                    console.log('跳转到首页，用户:', username);
                    window.location.href = '/';
                }, 1500);
            } else {
                // 登录失败
                showErrorMessage(data.message || '登录失败，请检查用户名和密码');
                loginBtn.disabled = false;
                loginBtn.querySelector('span:first-child').style.display = 'inline';
                loginBtn.querySelector('.btn-loading').style.display = 'none';
            }
        } catch (error) {
            console.error('登录失败:', error);
            showErrorMessage('网络错误，请稍后重试');
            loginBtn.disabled = false;
            loginBtn.querySelector('span:first-child').style.display = 'inline';
            loginBtn.querySelector('.btn-loading').style.display = 'none';
        }
    });
}

// 注册页面初始化
function initRegister() {
    const registerForm = document.getElementById('registerForm');
    const registerBtn = document.getElementById('registerBtn');
    const regPassword = document.getElementById('regPassword');
    const regConfirmPassword = document.getElementById('regConfirmPassword');
    
    // 密码强度检测
    regPassword.addEventListener('input', function() {
        checkPasswordStrength(this.value);
    });
    
    // 确认密码验证
    regConfirmPassword.addEventListener('input', function() {
        if (this.value && this.value !== regPassword.value) {
            showError('regConfirmPasswordError', '两次输入的密码不一致');
        } else {
            clearError('regConfirmPasswordError');
        }
    });
    
    registerForm.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const username = document.getElementById('regUsername').value;
        const email = document.getElementById('regEmail').value;
        const password = regPassword.value;
        const confirmPassword = regConfirmPassword.value;
        const agreeTerms = document.getElementById('agreeTerms').checked;
        
        // 清除之前的错误
        clearErrors('registerForm');
        
        // 验证输入
        let hasError = false;
        
        if (!username || username.length < 3 || username.length > 20) {
            showError('regUsernameError', '用户名长度应为3-20个字符');
            hasError = true;
        }
        
        if (!email || !isValidEmail(email)) {
            showError('regEmailError', '请输入有效的邮箱地址');
            hasError = true;
        }
        
        if (!password || password.length < 6) {
            showError('regPasswordError', '密码长度至少为6位');
            hasError = true;
        }
        
        if (password !== confirmPassword) {
            showError('regConfirmPasswordError', '两次输入的密码不一致');
            hasError = true;
        }
        
        if (!agreeTerms) {
            showError('termsError', '请同意用户协议和隐私政策');
            hasError = true;
        }
        
        if (hasError) {
            return;
        }
        
        // 显示加载状态
        registerBtn.disabled = true;
        registerBtn.querySelector('span:first-child').style.display = 'none';
        registerBtn.querySelector('.btn-loading').style.display = 'inline';
        
        try {
            console.log('准备发送注册请求:', { username, email });
            
            // 发送注册请求
            const response = await fetch('/api/register', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ username, email, password })
            });
            
            console.log('注册响应状态:', response.status);
            console.log('Content-Type:', response.headers.get('Content-Type'));
            
            // 检查响应类型
            const contentType = response.headers.get('Content-Type') || '';
            if (!contentType.includes('application/json')) {
                const text = await response.text();
                console.error('响应不是JSON:', text.substring(0, 200));
                throw new Error('服务器返回了非JSON数据: ' + text.substring(0, 100));
            }
            
            const data = await response.json();
            console.log('注册响应数据:', data);
            
            if (data.success) {
                // 注册成功
                showSuccessMessage('✅ 注册成功！正在跳转到首页...');
                
                // 保存用户信息
                localStorage.setItem('lastLoginUsername', username);
                
                // 延迟跳转
                setTimeout(() => {
                    console.log('注册成功，跳转到首页，用户:', username);
                    window.location.href = '/';
                }, 1500);
            } else {
                // 注册失败
                showErrorMessage(data.message || '注册失败，请稍后重试');
                registerBtn.disabled = false;
                registerBtn.querySelector('span:first-child').style.display = 'inline';
                registerBtn.querySelector('.btn-loading').style.display = 'none';
            }
        } catch (error) {
            console.error('注册失败:', error);
            showErrorMessage('网络错误，请稍后重试');
            registerBtn.disabled = false;
            registerBtn.querySelector('span:first-child').style.display = 'inline';
            registerBtn.querySelector('.btn-loading').style.display = 'none';
        }
    });
}

// 密码强度检测
function checkPasswordStrength(password) {
    const strengthBar = document.getElementById('strengthBar');
    const strengthFill = strengthBar.querySelector('.strength-fill');
    const strengthText = document.getElementById('strengthText');
    
    let strength = 0;
    let color = '#dc3545';
    let text = '弱';
    
    if (password.length >= 6) strength++;
    if (password.length >= 8) strength++;
    if (/[a-z]/.test(password) && /[A-Z]/.test(password)) strength++;
    if (/[0-9]/.test(password)) strength++;
    if (/[^a-zA-Z0-9]/.test(password)) strength++;
    
    switch (strength) {
        case 0:
        case 1:
            color = '#dc3545';
            text = '弱';
            break;
        case 2:
            color = '#ffc107';
            text = '中';
            break;
        case 3:
            color = '#fd7e14';
            text = '较强';
            break;
        default:
            color = '#28a745';
            text = '强';
    }
    
    strengthFill.style.width = (strength * 20) + '%';
    strengthFill.style.background = color;
    strengthText.textContent = text;
    strengthText.style.color = color;
}

// 显示错误
function showError(errorId, message) {
    const errorElement = document.getElementById(errorId);
    if (errorElement) {
        errorElement.textContent = message;
        // 添加对应的input error类
        const inputId = errorId.replace('Error', '');
        const input = document.getElementById(inputId);
        if (input) {
            input.classList.add('error');
        }
    }
}

// 清除错误
function clearError(errorId) {
    const errorElement = document.getElementById(errorId);
    if (errorElement) {
        errorElement.textContent = '';
        const inputId = errorId.replace('Error', '');
        const input = document.getElementById(inputId);
        if (input) {
            input.classList.remove('error');
        }
    }
}

// 清除所有错误
function clearErrors(formId) {
    const form = document.getElementById(formId);
    const errorMessages = form.querySelectorAll('.error-message');
    const inputs = form.querySelectorAll('input');
    
    errorMessages.forEach(error => {
        error.textContent = '';
    });
    
    inputs.forEach(input => {
        input.classList.remove('error');
    });
}

// 显示成功消息
function showSuccessMessage(message) {
    const successDiv = document.getElementById('successMessage');
    const errorBanner = document.getElementById('errorBanner');
    
    // 隐藏错误提示
    if (errorBanner) {
        errorBanner.classList.remove('show');
    }
    
    if (successDiv) {
        successDiv.textContent = message;
        successDiv.classList.add('show');
        
        setTimeout(() => {
            successDiv.classList.remove('show');
        }, 4000);
    }
}

// 显示错误横幅
function showErrorMessage(message) {
    const errorBanner = document.getElementById('errorBanner');
    const errorText = document.getElementById('errorText');
    const successDiv = document.getElementById('successMessage');
    
    // 隐藏成功提示
    if (successDiv) {
        successDiv.classList.remove('show');
    }
    
    if (errorBanner && errorText) {
        errorText.textContent = message;
        errorBanner.classList.add('show');
        
        // 5秒后自动隐藏
        setTimeout(() => {
            errorBanner.classList.remove('show');
        }, 5000);
    }
}

// 验证邮箱格式
function isValidEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

